package ai.people.core.plugin.listener;

import ai.people.core.plugin.properties.PluginProperties;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * 文件侦听器工厂
 *
 * @author yuanqinglong
 * @date 2022/6/13 19:07
 */
@Component
@RequiredArgsConstructor
public class JarListenerFactory {

    private final ConfigurableApplicationContext configurableApplicationContext;


    private final PluginProperties pluginProperties;

    private JarListener jarListener;

    @PostConstruct
    public void init(){
        jarListener = new JarListener(configurableApplicationContext);
    }

    public PluginProperties getPluginProperties() {
        return pluginProperties;
    }

    public JarListener getJarListener() {
        return jarListener;
    }

    /**
     * 时间间隔
     */
    private final long interval = TimeUnit.SECONDS.toMillis(1);

    /**
     * 获取监控
     *
     * @return {@link FileAlterationMonitor}
     */
    public FileAlterationMonitor getMonitor() {
        // 创建过滤器
        IOFileFilter directories = FileFilterUtils.and(FileFilterUtils.directoryFileFilter(), HiddenFileFilter.VISIBLE);
        IOFileFilter files = FileFilterUtils.and(FileFilterUtils.fileFileFilter(), FileFilterUtils.suffixFileFilter(".jar"));
        IOFileFilter filter = FileFilterUtils.or(directories, files);
        // 装配过滤器
        FileAlterationObserver observer = new FileAlterationObserver(new File(pluginProperties.getDir()), filter);
        // 向监听者添加监听器并注入业务服务
        observer.addListener(jarListener);
        // 返回监听者
        return new FileAlterationMonitor(interval, observer);
    }

}
